/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Base.js
 * @path:   js-src/Channel/
 * @desc:   Channel模块下基础业对象类
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
qui(
    function(require, exports, module) {


        Channel.Grid = function(options) {
            this.dao = Channel.Dao;
            this.config = Channel.Config;
            this.options = options || {};
        };

        Com.inherits(Channel.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.bindEvent();
                self._initBasicData();
            },
            fillGridByUrl: function() {
                var channelName = Ancestor.Util.getUrlId("channelName");
                if (channelName != null && channelName.length != 0) {
                    $("input[name='name']").val( decodeURIComponent(channelName) );
                }
            },

            run: function() {
                var self = this;
                self.fillGridByUrl();
                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                        Channel.Util.getType({
                            type: 'LiveChannelType',
                            cfgName: 'CHANNEL_TYPE',
                            errMsg: '频道类型获取失败',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });
                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                        Channel.Util.getType({
                            type: 'LiveType',
                            cfgName: 'LIVE_TYPE',
                            errMsg: '直播类型获取失败',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });
                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                        Channel.Util.getType({
                            type: 'LogType',
                            cfgName: 'LOG_TYPE',
                            errMsg: '获取日志类型失败',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });

                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                       auth.getAuthData({tips:1,url: '/epg/env_config_list.html'},function (rt) {
                           if (rt == null) {
                             //   this.config.AUTH_CHECK.sys_config = true;
                               $("a[name=configslink]").show();
                           }
                           ajaxBasicRequestLen()
                       })
                    }
                });

                this.ajaxBasicRequestManage.init(this, function(obj) {
                    obj.start();
                });

            },

            start: function(options, callback) {
                var self = this;
                self.init();

                var gridConfig = self.getGridConfig();
                //self.echoQuery();

                options = $.extend(true, {
                    // width: 1500,
                    //  shrinkToFit: false,
                    //autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);

                $('body').on('click', 'a.disabled', function(e) {
                    e.preventDefault();
                });

                $('#resetFrm').click(function() {
                    $('select[name="type"]').html('<option value="">请选择</option>');
                    $('select[name="type"]').hide();
                });
            },


            _initBasicData: function() {

                var html = '';
                $.each(Channel.Config.LIVE_TYPE, function(i, n) {
                    if (n != undefined) {
                        html += '<option value="' + i + '">' + n + '</option>';
                    }

                });

                $('select[name="liveType"]').append(html);



                Channel.Config.NormalChannel = {},
                    Channel.Config.TempChannel = {},
                    Channel.Config.Carousel = {};

                $.each(Channel.Config.CHANNEL_TYPE, function(i, n) {

                    if (n != undefined) {
                        if (n.indexOf("临时") == -1) {
                            if (n.indexOf("爱奇艺") == -1)
                                Channel.Config.NormalChannel[i] = n;
                            else
                                Channel.Config.Carousel[i] = n;
                        } else {
                            Channel.Config.TempChannel[i] = n;
                        }
                    }

                });

            },

            initGrid: function(options, callback) {
                var self = this;
                var params = self.getParam();

                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');
                //params.rowNum=10;

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                    postData: $.extend(true, {}, params),

                }, gridConfig, options);

                //   $grid.jqGrid('scroll', {});

                //console.log(options   );

                $grid.jqGrid(options);

            },
            jsonConvert: function(jsonstr, o) {
                if (jsonstr && typeof jsonstr === 'string') {
                    var _jsonparse = false;
                    if ($.jgrid.useJSON) {
                        $.jgrid.useJSON = false;
                        _jsonparse = true;
                    }
                    var json = $.jgrid.parse(jsonstr);
                    if (_jsonparse) {
                        $.jgrid.useJSON = true;
                    }
                    var gprm = json[o.jsonGrid.config];
                    var jdata = json[o.jsonGrid.data];
                    if (jdata) {
                        var svdatatype = gprm.datatype;
                        gprm.datatype = 'jsonstring';
                        gprm.datastr = jdata;
                        $($t).jqGrid(gprm).jqGrid("setGridParam", {
                            datatype: svdatatype
                        });
                    } else {
                        $($t).jqGrid(gprm);
                    }
                }
            },
            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();

                /*
                Channel.Config.TABLE.jsonReader ={  

                     root:"data.result",  

                     page: "data.pageNo",  

                     total: "data.totalCount/data.pageSize",  

                     records: "data.totalCount",

                 };
*/

                $grid.jqGrid('setGridParam', {
                    postData: params,
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },


            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function() {
                    return true; //this.name; 
                });

                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {

                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';

                    }

                });

                return params;

            },

            bindEvent: function() {
                var self = this;
                self.bindBasicEvent();
            },


            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    var validator = Channel.Util.getValidator($form, Channel.Config.SEARCH);

                    if (!validator.form())
                        return;

                    self.query();
                    return false;
                });

                $("div.query").keydown(function(event) {
                    if (event.keyCode == 13) {
                        var validator = Channel.Util.getValidator($form, Channel.Config.SEARCH);
                        if (!validator.form())
                            return;

                        self.query();
                        return false;
                    }
                });

                $form.find('button[type="reset"]').click(function() {
                    self.resetQueryForm();
                });

                $('select[name="liveType"]').click(function() {

                    var html = '<option value="">请选择</option>';

                    if ($(this).val() == 1) {
                        $.each(Channel.Config.NormalChannel, function(i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });

                    } else if ($(this).val() == 2) {
                        $.each(Channel.Config.TempChannel, function(i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                    } else if ($(this).val() == 3) {
                        $.each(Channel.Config.Carousel, function(i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                    } else {
                        html = '';
                    }

                    if (html != '') {
                        $('select[name="type"]').show();
                    } else
                        $('select[name="type"]').hide();

                    $('select[name="type"]').html(html);

                });
            },

            bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "minDate", selectedDate);
                    },

                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "maxDate", selectedDate);
                    },

                });

                fillFieldNameWhenChangeSelect($form, 'query-select-control', 'query-input-text');
            },

        });

    }
);